<template>
  <div class="batch-center">
    <div class="container">
      <!-- 操作栏 -->
      <div class="action-bar card">
        <div class="action-buttons">
          <button class="btn btn-primary" @click="openCreateDialog">
            <PlusIcon :size="14" />
            新建批次
          </button>
        </div>
        <div class="filter-selectors">
          <div class="selector-group">
            <label>品牌：</label>
            <select v-model="selectedBrand" class="select" @change="handleFilterChange">
              <option value="">全部品牌</option>
              <option v-for="brand in brands" :key="brand.id" :value="brand.name">
                {{ brand.name }}
              </option>
            </select>
          </div>
          <div class="selector-group">
            <label>季次：</label>
            <select v-model="selectedSeason" class="select" @change="handleFilterChange">
              <option value="">全部季次</option>
              <option v-for="season in seasons" :key="season.id" :value="season.name">
                {{ season.name }}
              </option>
            </select>
          </div>
          <div class="view-toggle">
            <button
              class="btn"
              :class="{ 'btn-primary': viewMode === 'card' }"
              @click="viewMode = 'card'"
            >
              卡片视图
            </button>
            <button
              class="btn"
              :class="{ 'btn-primary': viewMode === 'table' }"
              @click="viewMode = 'table'"
            >
              表格视图
            </button>
            <label class="show-archived-checkbox">
              <input
                type="checkbox"
                v-model="showArchived"
                class="checkbox-input"
                @change="handleFilterChange"
              />
              <span class="checkbox-label">显示归档</span>
            </label>
          </div>
        </div>
      </div>

      <!-- 新建批次弹窗 -->
      <CreateBatchDialog
        :visible="createDialogVisible"
        :brands="brands"
        :seasons="seasons"
        @close="closeCreateDialog"
        @created="handleBatchCreated"
        @conflict="handleBatchConflict"
      />

      <!-- 编辑批次弹窗 -->
      <CreateBatchDialog
        :visible="editDialogVisible"
        :brands="brands"
        :seasons="seasons"
        :edit-mode="true"
        :batch-data="editingBatch"
        @close="closeEditDialog"
        @updated="handleBatchUpdated"
      />

      <!-- 导入弹窗 -->
      <ImportDialog
        :visible="importDialogVisible"
        :batch-id="importingBatchId"
        :current-batch="importingBatch"
        :brands="brands"
        @close="closeImportDialog"
        @cancel="closeImportDialog"
        @start-upload="handleStartUpload"
      />

      <!-- 删除确认弹窗 -->
      <DeleteBatchDialog
        :visible="deleteDialogVisible"
        :batch="deletingBatch"
        @confirm="handleDeleteConfirm"
        @close="handleDeleteCancel"
      />

      <!-- 批次列表 -->
      <div class="batch-list">
        <!-- 卡片视图 -->
        <div v-if="viewMode === 'card'" class="batch-cards">
          <BatchCard
            v-for="batch in batches"
            :key="batch.id"
            :batch="batch"
            :brands="brands"
            :is-uploading="uploadingBatchId === String(batch.id)"
            :upload-progress="uploadingBatchId === String(batch.id) ? uploadProgress : {}"
            :is-flashing="String(flashingBatchId) === String(batch.id)"
            @enter-matching="enterMatching"
            @edit="handleEdit"
            @archive="handleArchive"
            @import="handleImport"
            @update-vectors="handleUpdateVectors"
            @delete="handleDelete"
            @stop-import="handleStopImport"
          />
        </div>

        <!-- 表格视图 -->
        <BatchTable
          v-else
          :batches="batches"
          :brands="brands"
          :flashing-batch-id="String(flashingBatchId)"
          @enter-matching="enterMatching"
          @edit="handleEdit"
          @archive="handleArchive"
          @import="handleImport"
          @update-vectors="handleUpdateVectors"
          @delete="handleDelete"
          @stop-import="handleStopImport"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useBatchStore } from '../stores/batchStore'
import { createBatchButtonManager } from '../utils/buttonStateManager'
import {
  getBatches,
  getBrands,
  getSeasons,
  stopBatchImport,
  archiveBatch,
  unarchiveBatch,
  updateBatchVectors,
  deleteBatch,
  createBatch,
  updateBatch,
  importBatchData,
} from '../api/batchApi'
import { testStatusFix } from '../utils/batchUtils'
import CreateBatchDialog from '../components/CreateBatchDialog.vue'
import BatchCard from '../components/BatchCard.vue'
import BatchTable from '../components/BatchTable.vue'
import ImportDialog from '../components/ImportDialog.vue'
import DeleteBatchDialog from '../components/DeleteBatchDialog.vue'

import { PlusIcon, UploadIcon } from '../components/icons'
import { ElMessage } from 'element-plus'

export default {
  name: 'BatchCenter',
  components: {
    CreateBatchDialog,
    BatchCard,
    BatchTable,
    ImportDialog,
    DeleteBatchDialog,

    PlusIcon,
    UploadIcon,
  },
  setup() {
    const router = useRouter()
    const batchStore = useBatchStore()
    const viewMode = ref('card')
    const selectedBrand = ref('')
    const selectedSeason = ref('')
    const showArchived = ref(false)
    const batches = ref([])
    const brands = ref([])
    const seasons = ref([])
    const loading = ref(false)
    const createDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const editingBatch = ref(null)
    const importDialogVisible = ref(false)
    const importingBatchId = ref('')
    const deleteDialogVisible = ref(false)
    const deletingBatch = ref(null)

    // 上传进度相关状态
    const uploadingBatchId = ref(null)
    const uploadProgress = ref({
      imageFileName: '',
      imageFileSize: 0,
      imageProgress: 0,
      productFileName: '',
      productFileSize: 0,
      productProgress: 0,
      currentFile: '',
      uploadSpeed: 0,
    })

    // 冲突批次闪烁状态
    const flashingBatchId = ref(null)

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        const [batchesData, brandsData, seasonsData] = await Promise.all([
          getBatches({
            brand: selectedBrand.value,
            season: selectedSeason.value,
            showArchived: showArchived.value,
          }),
          getBrands(),
          getSeasons(),
        ])

        batches.value = batchesData.list
        // 同时更新全局状态，供面包屑使用
        batchStore.setBatches(batchesData.list)
        brands.value = brandsData
        seasons.value = seasonsData
      } catch (error) {
        console.error('加载数据失败:', error)
        batches.value = []
        brands.value = []
        seasons.value = []
      } finally {
        loading.value = false
      }
    }

    // 根据品牌、季次和归档状态筛选批次
    const filteredBatches = computed(() => {
      return batches.value.filter(batch => {
        // 品牌筛选
        if (selectedBrand.value && batch.brand !== selectedBrand.value) {
          return false
        }
        // 季次筛选
        if (selectedSeason.value && batch.season !== selectedSeason.value) {
          return false
        }
        // 归档状态筛选
        if (!showArchived.value && batch.status === 'archived') {
          return false
        }
        return true
      })
    })

    // 根据importingBatchId获取对应的批次对象
    const importingBatch = computed(() => {
      if (!importingBatchId.value) return null
      return batches.value.find(batch => String(batch.id) === importingBatchId.value)
    })

    const enterMatching = batchId => {
      // 在跳转前设置当前批次到全局状态
      const batch = batches.value.find(b => b.id === batchId)
      if (batch) {
        batchStore.setCurrentBatch(batch)
      }
      router.push(`/matching-workbench/${batchId}`)
    }

    const handleArchive = async batchId => {
      const buttonManager = createBatchButtonManager(batchId)

      buttonManager.debounce(`archive_${batchId}`, async () => {
        try {
          buttonManager.setProcessing(`archive_${batchId}`, true)

          // 根据批次状态决定调用归档还是取消归档API
          const batch = batches.value.find(b => b.id === batchId)
          if (batch && batch.status === 'archived') {
            // 如果批次已归档，则调用取消归档API
            await unarchiveBatch(batchId)
          } else {
            // 否则调用归档API
            await archiveBatch(batchId)
          }

          // 刷新数据以显示更新后的状态
          await loadData()
        } catch (error) {
          console.error('归档/取消归档批次失败:', error)
          ElMessage.error('归档操作失败')
        } finally {
          buttonManager.setProcessing(`archive_${batchId}`, false)
        }
      })
    }

    const handleImport = batchId => {
      importingBatchId.value = String(batchId) // 确保batchId是字符串类型

      importDialogVisible.value = true
    }

    const handleUpdateVectors = async batchId => {
      const buttonManager = createBatchButtonManager(batchId)

      buttonManager.debounce(`update-vectors_${batchId}`, async () => {
        try {
          buttonManager.setProcessing(`update-vectors_${batchId}`, true)

          const res = await updateBatchVectors(batchId)
          console.log('更新向量库结果:', res)
          if (res.code === 200) {
            ElMessage.success(res.message || '更新向量库成功')
            // 刷新数据
            await loadData()
          } else {
            ElMessage.error(res.message)
          }
        } catch (error) {
          console.error('更新向量库失败:', error)
          ElMessage.error('更新向量库失败')
        } finally {
          buttonManager.setProcessing(`update-vectors_${batchId}`, false)
        }
      })
    }

    const handleEdit = batch => {
      editingBatch.value = batch
      editDialogVisible.value = true
    }

    const handleDelete = batch => {
      deletingBatch.value = batch
      deleteDialogVisible.value = true
    }

    const handleDeleteConfirm = async batchId => {
      try {
        const res = await deleteBatch(batchId)
        console.log('删除结果:', res)
        if (res.code === 200) {
          ElMessage.success(res.message || '删除成功')
          deleteDialogVisible.value = false
          await loadData()
        } else {
          ElMessage.error(res.message)
        }
        // 刷新数据
        // 关闭弹窗
        deletingBatch.value = null
      } catch (error) {
        console.error('删除批次失败:', error)
        // 这里可以添加错误提示
      }
    }

    const handleDeleteCancel = () => {
      deleteDialogVisible.value = false
      deletingBatch.value = null
    }

    const handleStopImport = async batchId => {
      try {
        await stopBatchImport(batchId)
        // 刷新数据以显示更新后的状态
        await loadData()
      } catch (error) {
        console.error('停止导入失败:', error)
        // 这里可以添加错误提示
      }
    }

    const openCreateDialog = () => {
      createDialogVisible.value = true
    }

    const closeCreateDialog = () => {
      createDialogVisible.value = false
    }

    const handleBatchCreated = async created => {
      console.log('🚀 ~ handleBatchCreated ~ created:', created)
      // 关闭弹窗并刷新列表
      createDialogVisible.value = false
      await loadData()
    }

    const handleBatchConflict = conflictData => {
      const conflictBatchId = conflictData.conflict_batch_id

      // 设置闪烁的批次ID - 确保类型一致
      flashingBatchId.value = String(conflictBatchId)

      // 5秒后停止闪烁
      setTimeout(() => {
        flashingBatchId.value = null
      }, 5000)
    }

    const closeEditDialog = () => {
      editDialogVisible.value = false
      editingBatch.value = null
    }

    const handleBatchUpdated = async updated => {
      editDialogVisible.value = false
      editingBatch.value = null
      await loadData()
    }

    const closeImportDialog = () => {
      importDialogVisible.value = false
      importingBatchId.value = ''
    }

    const handleStartUpload = async uploadData => {
      try {
        const { imageFile, excelFile, importMode, batchId: uploadDataBatchId } = uploadData

        // 优先使用uploadData中的batchId，如果为空则使用importingBatchId
        const batchId = uploadDataBatchId || importingBatchId.value

        // 初始化上传进度
        uploadProgress.value = {
          imageFileName: imageFile.name,
          imageFileSize: imageFile.size,
          imageProgress: 0,
          productFileName: excelFile.name,
          productFileSize: excelFile.size,
          productProgress: 0,
          currentFile: 'image_package',
          uploadSpeed: 0,
        }
        uploadingBatchId.value = batchId

        // 关闭导入弹窗，开始上传
        closeImportDialog()

        // 创建FormData并添加文件
        const formData = new FormData()
        formData.append('image_package', imageFile)
        formData.append('product_info', excelFile)
        formData.append('import_mode', importMode)

        // 上传进度回调函数
        const onUploadProgress = progressEvent => {
          const { loaded, total } = progressEvent
          const totalBytes = imageFile.size + excelFile.size
          const uploadedBytes = loaded

          // 计算上传速度
          const now = Date.now()
          if (!onUploadProgress.startTime) {
            onUploadProgress.startTime = now
            onUploadProgress.lastLoaded = 0
          }

          const elapsed = (now - onUploadProgress.startTime) / 1000
          const speed = elapsed > 0 ? (loaded - onUploadProgress.lastLoaded) / elapsed : 0
          uploadProgress.value.uploadSpeed = speed

          // 更新进度 - 前端完全控制
          if (uploadedBytes <= imageFile.size) {
            // 还在上传图片包
            const imageProgress = Math.min(100, (uploadedBytes / imageFile.size) * 100)
            uploadProgress.value.imageProgress = imageProgress
            uploadProgress.value.currentFile = 'image_package'
          } else {
            // 图片包上传完成，开始上传商品信息
            uploadProgress.value.imageProgress = 100
            const remainingBytes = uploadedBytes - imageFile.size
            const productProgress = Math.min(100, (remainingBytes / excelFile.size) * 100)
            uploadProgress.value.productProgress = productProgress
            uploadProgress.value.currentFile = 'product_info'
          }

          onUploadProgress.lastLoaded = loaded
        }

        // 调用导入API
        const res = await importBatchData(batchId, formData, importMode, onUploadProgress)

        // 确保显示100%进度
        uploadProgress.value.imageProgress = 100
        uploadProgress.value.productProgress = 100
        uploadProgress.value.currentFile = ''

        if (res.code === 200) {
          // 上传成功
          ElMessage.success('导入成功')
          // 延迟清除状态，让用户看到完成状态
          setTimeout(() => {
            uploadingBatchId.value = null
            uploadProgress.value = {}
          }, 1000)
          // 上传完成后刷新数据
          await loadData()
        } else {
          // 上传失败
          ElMessage.error(res.message || '导入失败')
          uploadingBatchId.value = null
          uploadProgress.value = {}
        }
      } catch (error) {
        console.error('导入失败:', error)
        ElMessage.error(error.message || '导入失败，请重试')
        uploadingBatchId.value = null
        uploadProgress.value = {}
      }
    }

    // 监听筛选条件变化，重新加载数据
    const handleFilterChange = () => {
      loadData()
    }

    // 组件挂载时加载数据
    onMounted(() => {
      // 在开发环境下测试状态修复逻辑
      testStatusFix()
      loadData()
    })

    return {
      batches: filteredBatches,
      brands,
      seasons,
      selectedBrand,
      selectedSeason,
      showArchived,
      viewMode,
      enterMatching,
      handleEdit,
      handleArchive,
      handleImport,
      handleUpdateVectors,
      handleDelete,
      handleDeleteConfirm,
      handleDeleteCancel,
      handleStopImport,
      loading,
      createDialogVisible,
      openCreateDialog,
      closeCreateDialog,
      handleBatchCreated,
      editDialogVisible,
      editingBatch,
      closeEditDialog,
      handleBatchUpdated,
      importDialogVisible,
      importingBatchId,
      importingBatch,
      closeImportDialog,
      handleStartUpload,
      deleteDialogVisible,
      deletingBatch,
      handleFilterChange,
      uploadProgress,
      uploadingBatchId,
      flashingBatchId,
      handleBatchConflict,
    }
  },
}
</script>

<style scoped>
/* 页面容器样式 */
.batch-center {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-selectors {
  display: flex;
  gap: 16px;
  align-items: center;
}

.selector-group {
  display: flex;
  align-items: center;
  gap: 6px;
}

.selector-group label {
  font-size: 14px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.selector-group .select {
  min-width: 120px;
}

.batch-list {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.view-toggle {
  display: flex;
  gap: 8px;
  align-items: center;
}

.show-archived-checkbox {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-secondary);
  user-select: none;
}

.checkbox-input {
  width: 14px;
  height: 14px;
  cursor: pointer;
  accent-color: var(--primary-color);
}

.checkbox-label {
  font-size: 14px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.batch-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
  gap: 16px;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  align-items: start;
}

@media (max-width: 768px) {
  .batch-cards {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .btn {
    justify-content: center;
  }

  .filter-selectors {
    flex-direction: column;
    margin-left: 0;
    gap: 12px;
  }
}
</style>
